package cn.cena.user.intercept;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;


/**
 * 登录拦截器
 */
@Component
public class LoginIntercept implements HandlerInterceptor{

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 重redis中取数据
        if(!StringUtils.isEmpty(token)){
            Object o = redisTemplate.opsForValue().get(token);
            if (o != null){ // 没有过期
                // 重新存入redis，目的刷新时间
                redisTemplate.opsForValue().set(token, o, 30, TimeUnit.MINUTES);

                // 放行
                return true;
            }
        }
        // 过期了
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        // 写好一段信息返回到前端
        writer.write("{\"success\":false,\"msg\":\"登录过期\"}");
        writer.close();
        return false;
    }
}
